﻿using AutoMapper;
using Common.Damin;
using Common.Infrastructrue.Interface;
using Common.Service;
using MediatR;
using Microsoft.OpenApi.Writers;
using RabitPart.WritedPartApi.Application.Comman.RBACfile;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Transactions;

namespace RabitPart.WritedPartApi.Application.CommanHandel.RBACfile
{
    public class RBACUserCreateCommanHandel : IRequestHandler<RBACUserCreateComman, ApiResult>
    {
        private readonly IUserResponstity userRE;
        private readonly IRel_user_roleResponstity userroleRE;
        private readonly IMapper _mapper;
        private readonly ILogger<RBACUserCreateCommanHandel> logger;
        public RBACUserCreateCommanHandel(IUserResponstity userRE, IMapper mapper, ILogger<RBACUserCreateCommanHandel> logger, IRel_user_roleResponstity userroleRE)
        {
            this.userRE = userRE;
            _mapper = mapper;
            this.userroleRE = userroleRE;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(RBACUserCreateComman request, CancellationToken cancellationToken)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
                try
                {
                    //先将用户添加到用户表，以便获取子赠的用户id
                    var userlist = _mapper.Map<User>(request);
                    //添加时间
                    userlist.CreateDate = DateTime.Now;
                    userlist.CreateOperatorName = "添加信息";
                    //插入用户记录表，此时数据库会自增ID冰天回到userlist.Userid中
                    await userRE.InsertAsync(userlist);

                    //插入用户记录，此时数据库会发生可以通过角色仓库的某个方法来验证，比如获取角色是否存在
                    var role = await userroleRE.GetAsync(x => x.rId == request.rId);
                    if (role == null)
                    {
                        return ApiResult.Fail($"该用户ID不存在:{request.rId}", StatusCodeEnum.Fail);
                    }

                    //获取自增的用户ID用于构建用户角色关联
                    int userId = userlist.uId;

                    //创建用户角色关联实体
                    Rel_user_role userrole = new Rel_user_role()
                    {
                        uId = userId,
                        rId = request.rId,
                        userroleTime = DateTime.Now,
                    };

                    //向用户角色插入关联记录
                    await userroleRE.InsertAsync(userrole);

                    //提交事务
                    scope.Complete();
                    return ApiResult.Success(StatusCodeEnum.Ok);

                }
                finally
                {
                    //事务回滚
                    scope.Dispose();
                }
            }
            catch (Exception ex)
            {
                logger.LogError("添加用户异常" + ex.Message);
                return await Task.FromResult(ApiResult.Fail(ex.Message, StatusCodeEnum.Fail));
            }
        }
    }
}
